using System;
using TTEngine;
using Silk.NET.OpenGLES;

namespace TTEngine.Graphics
{

    public class UniformBlock : IDisposable
    {
        private static UniformBlock _empty;
        private readonly uint _buffer;
        private bool _disposed;

        public static UniformBlock GetEmpty()
        {
            if (_empty == null)
            {
                _empty = new UniformBlock();
            }
            return _empty;
        }

        public static int GetMax()
        {
            int value = TTEngine.Runtime.activeGL.GetProgram(0, ProgramPropertyARB.ActiveUniformBlocks);
            return value == 0 ? -1 : value;
        }

        public UniformBlock()
        {
            _buffer = TTEngine.Runtime.activeGL.GenBuffer();
        }

        public uint GetGLBuffer()
        {
            return _buffer;
        }

        public void UploadData(byte[] data, bool dynamic)
        {
            TTEngine.Runtime.activeGL.BindBuffer(BufferTargetARB.UniformBuffer, _buffer);
            unsafe
            {
                fixed (void* ptr = data)
                {
                    TTEngine.Runtime.activeGL.BufferData(BufferTargetARB.UniformBuffer, (UIntPtr)data.Length, ptr, dynamic ? BufferUsageARB.DynamicDraw : BufferUsageARB.StaticDraw);
                }
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                TTEngine.Runtime.activeGL.DeleteBuffer(_buffer);
                _disposed = true;
            }
        }
    }
}